/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-06-29 16:42:31
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-05-08 18:25:44
 * @FilePath: \report-h5\src\utils\WXAuth.ts
 */
import { getUserInfoByCode } from '@/apis/wx'
import { storage } from '@/store/sessionStorage'
import { getQueryVariable } from '.'
import { appId } from './config'
import { userStore } from '@/store/user.store'

export class WxAuth {
    private code = ''
    private url = ''
    private locationUrl = ''
    private wxUserInfo: any
    private uStore = userStore()
    constructor(callback = (arg: any) => {}) {
        this.locationUrl = window.location.origin
        this.wxUserInfo = storage.get('wxUserInfo') ? JSON.parse(storage.get('wxUserInfo')) : null
        console.log('wxUserInfo', this.wxUserInfo)

        this.url = this.getAuthUrl(appId, this.locationUrl)
        console.log('url', window.location.href, this.url)
        this.code = getQueryVariable('code') || ''
        console.log('code', this.code)

        //判断本地是否有用户信息数据
        if (!this.wxUserInfo) {
            //通过code判断是 授权返回 还是默认进入页面
            console.log(this.wxUserInfo)
            if (this.code) {
                //通过接口获取用户信息
                getUserInfoByCode(this.code).then(res => {
                    if (res.data.value === 200) {
                        //判断用户是否授权过
                        if (res.data.data) {
                            storage.set('wxUserInfo', JSON.stringify(res.data.data))
                            this.uStore.isAuth = true
                            callback(res.data.data.headImgUrl)
                        } else {
                            //返回 null 进行授权
                            this.uStore.isAuth = false
                            window.location.href = this.url
                        }
                    }
                })
            } else {
                window.location.href = this.url
            }
        } else {
            callback(this.wxUserInfo.headImgUrl)
        }
    }
    private getAuthUrl = (appId: string, currentPageUrl: string) => {
        const authUrl =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
            appId +
            '&redirect_uri=' +
            encodeURIComponent(currentPageUrl) +
            '&response_type=code&scope=snsapi_userinfo&state=TOKEN&connect_redirect=1#wechat_redirect'
        return authUrl
    }
}
